<template>
  <div class="customer-service-container">
    <!-- 左侧聊天列表 -->
    <div class="conversation-list">
      <div class="list-header">
        <h3>我的消息</h3>
      </div>
      <div class="list-content">
        <div
          v-for="conversation in conversations"
          :key="conversation.id"
          class="conversation-item"
          :class="{ active: currentConversation?.id === conversation.id }"
          @click="selectConversation(conversation)"
        >
          <div class="store-avatar">
            <span class="store-avatar-text">{{
              conversation.storeName?.[0] || "S"
            }}</span>
          </div>
          <div class="conversation-info">
            <div class="conversation-header">
              <span class="store-name">{{
                conversation.storeName || "未知店铺"
              }}</span>
              <span class="last-time">{{
                formatLastTime(conversation.lastMessageTime || "")
              }}</span>
            </div>
            <div class="conversation-preview">
              <span class="last-message">{{
                conversation.lastMessage || "暂无消息"
              }}</span>
              <a-badge
                v-if="conversation.unreadCount && conversation.unreadCount > 0"
                :count="conversation.unreadCount"
                class="unread-badge"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间聊天区域 -->
    <div class="chat-panel" v-if="currentConversation">
      <!-- 聊天标题 -->
      <div class="chat-header">
        <h3>{{ currentConversation.storeName }}</h3>
      </div>
      <!-- 聊天记录 -->
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="[
            'message',
            msg.senderType === 0 ? 'message-sent' : 'message-received',
          ]"
        >
          <div class="message-content">
            <p>{{ msg.content || "" }}</p>
            <span class="message-time">{{
              formatMessageTime(msg.createdAt)
            }}</span>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-actions">
          <a-upload
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @change="handleImageUpload"
          >
            <a-button type="text">
              <picture-outlined />
            </a-button>
          </a-upload>
        </div>
        <a-textarea
          v-model:value="inputMessage"
          :rows="3"
          placeholder="请输入消息..."
          :maxLength="500"
          @pressEnter.prevent="sendMessage"
        />
        <a-button
          type="primary"
          class="send-button"
          :disabled="!inputMessage.trim()"
          @click="sendMessage"
        >
          发送
        </a-button>
      </div>
    </div>

    <!-- 右侧商品信息 -->
    <div class="product-info-panel">
      <div class="product-card" v-if="product">
        <img
          :src="product.imageUrl"
          :alt="product.name"
          class="product-image"
          @error="handleImageError"
        />
        <div class="product-details">
          <h3 class="product-name">{{ product.name }}</h3>
          <p class="product-price">¥{{ product.price?.toFixed(2) }}</p>
        </div>
      </div>
      <div class="store-info" v-if="store">
        <img
          :src="store.imageUrl"
          :alt="store.name"
          class="store-logo"
          @error="handleImageError"
        />
        <div class="store-details">
          <div class="store-name">{{ store.name }}</div>
          <div class="store-status online">在线</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { PictureOutlined } from "@ant-design/icons-vue";
import { getProductUsingGet } from "@/api/shangpinjiekou";
import { getStoreInfoUsingPost } from "@/api/storeController";
import { uploadFileUsingPost } from "@/api/cosController";
import {
  listUserConversationsUsingPost,
  startUserConversationUsingPost,
  getUserConversationDetailUsingPost,
  sendUserMessageUsingPost,
} from "@/api/conversationController";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import type API from "@/api";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const route = useRoute();
const router = useRouter();
const product = ref<API.ClothingProduct>();
const store = ref<API.Store>();
const inputMessage = ref("");
const messagesContainer = ref<HTMLElement>();
const conversations = ref<API.ConversationVO[]>([]);
const currentConversation = ref<API.ConversationVO>();
const isFromContactButton = ref(false);

// 修改消息类型定义以完全匹配API的MessageVO类型
interface Message {
  id?: number;
  senderId?: number;
  senderType?: number;
  content?: string; // 修改为可选
  type?: number;
  isRead?: boolean;
  sequence?: string;
  createdAt?: string | null;
}

const messages = ref<Message[]>([]);

// 添加轮询间隔变量
const MESSAGE_POLL_INTERVAL = 3000; // 3秒
const messagePollingTimer = ref<number>();
const storePollingTimer = ref<number>();

// 轮询获取最新消息
const pollNewMessages = async () => {
  if (!currentConversation.value?.id) return;

  try {
    const res = await getUserConversationDetailUsingPost({
      conversationId: currentConversation.value.id,
    });

    if (res.data?.code === 0 && res.data.data) {
      // 合并用户消息和商家消息，并按sequence排序
      const allMessages = [
        ...(res.data.data.userMessages || []),
        ...(res.data.data.storeMessages || []),
      ].sort((a, b) => Number(a.sequence || 0) - Number(b.sequence || 0));

      // 只有当消息数量或最后一条消息不同时才更新
      const lastNewMessage = allMessages[allMessages.length - 1];
      const lastCurrentMessage = messages.value[messages.value.length - 1];

      if (
        allMessages.length !== messages.value.length ||
        lastNewMessage?.sequence !== lastCurrentMessage?.sequence
      ) {
        messages.value = allMessages as Message[];
        await nextTick();
        scrollToBottom();
      }
    }
  } catch (error) {
    console.error("轮询消息失败:", error);
  }
};

// 轮询获取店铺信息
const pollStoreInfo = async () => {
  if (!store.value?.id) return;

  try {
    const storeRes = await getStoreInfoUsingPost({ storeId: store.value.id });
    if (storeRes.data?.code === 0 && storeRes.data.data) {
      store.value = storeRes.data.data;
    }
  } catch (error) {
    console.error("轮询店铺信息失败:", error);
  }
};

// 开始轮询
const startPolling = () => {
  // 清除可能存在的旧定时器
  stopPolling();

  // 开始消息轮询
  messagePollingTimer.value = window.setInterval(
    pollNewMessages,
    MESSAGE_POLL_INTERVAL
  );

  // 开始店铺信息轮询
  storePollingTimer.value = window.setInterval(
    pollStoreInfo,
    MESSAGE_POLL_INTERVAL
  );
};

// 停止轮询
const stopPolling = () => {
  if (messagePollingTimer.value) {
    clearInterval(messagePollingTimer.value);
    messagePollingTimer.value = undefined;
  }
  if (storePollingTimer.value) {
    clearInterval(storePollingTimer.value);
    storePollingTimer.value = undefined;
  }
};

// 加载商品和店铺信息
const loadData = async () => {
  try {
    const productId = Number(route.params.productId);
    const storeId = Number(route.params.storeId);
    isFromContactButton.value = route.query.from === "contact";

    if (productId) {
      const productRes = await getProductUsingGet({ id: productId });
      if (productRes.data?.code === 0 && productRes.data.data) {
        product.value = productRes.data.data;
      }
    }

    if (storeId) {
      const storeRes = await getStoreInfoUsingPost({ storeId });
      if (storeRes.data?.code === 0 && storeRes.data.data) {
        store.value = storeRes.data.data;

        // 如果是从联系客服按钮进入，先创建新会话
        if (isFromContactButton.value) {
          await startNewConversation(storeId);
        }

        // 开始轮询
        startPolling();
      }
    }
  } catch (error) {
    message.error("加载信息失败");
  }
};

// 创建新会话
const startNewConversation = async (storeId: number) => {
  try {
    const res = await startUserConversationUsingPost({
      storeId: storeId,
    } as API.CreateConversationRequest);

    if (res.data?.code === 0 && res.data.data) {
      currentConversation.value = res.data.data;
      if (res.data.data.id) {
        await loadConversationDetail(Number(res.data.data.id));
      }
      await loadConversations();
    }
  } catch (error) {
    message.error("创建会话失败");
  }
};

// 加载会话详情
const loadConversationDetail = async (conversationId: number) => {
  try {
    const res = await getUserConversationDetailUsingPost({
      conversationId,
    });

    if (res.data?.code === 0 && res.data.data) {
      currentConversation.value = res.data.data;

      // 合并用户消息和商家消息，并按sequence排序
      const allMessages = [
        ...(res.data.data.userMessages || []),
        ...(res.data.data.storeMessages || []),
      ].sort((a, b) => Number(a.sequence || 0) - Number(b.sequence || 0));

      messages.value = allMessages as Message[];
      await nextTick();
      scrollToBottom();
    }
  } catch (error) {
    message.error("加载会话详情失败");
  }
};

// 选择会话
const selectConversation = async (conversation: API.ConversationVO) => {
  const conversationId = conversation.id;
  if (!conversationId) return;
  currentConversation.value = conversation;
  await loadConversationDetail(conversationId);
  // 重新开始轮询
  startPolling();
};

// 格式化最后消息时间
const formatLastTime = (time: string) => {
  if (!time) return "";
  return dayjs(time).fromNow();
};

// 修改发送消息逻辑
const sendMessage = async () => {
  if (!inputMessage.value.trim() || !currentConversation.value?.id) return;

  try {
    const messageRequest: API.SendMessageRequest = {
      conversationId: currentConversation.value.id,
      content: inputMessage.value.trim(),
    };

    const res = await sendUserMessageUsingPost(messageRequest);
    if (res.data?.code === 0 && res.data.data) {
      // 添加新消息到消息列表
      messages.value.push({
        content: inputMessage.value.trim(),
        senderType: 0, // 用户发送
        sequence: Date.now().toString(),
        createdAt: new Date().toISOString(),
      });

      // 清空输入框
      inputMessage.value = "";

      // 滚动到底部
      await nextTick();
      scrollToBottom();
    } else {
      message.error(res.data?.message || "发送失败");
    }
  } catch (error) {
    message.error("发送消息失败");
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 处理图片上传
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    message.error("只能上传图片文件！");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片必须小于 2MB！");
    return false;
  }
  return true;
};

// 修改图片上传处理函数
const handleImageUpload = async (info: any) => {
  if (info.file.status === "uploading") {
    return;
  }
  if (info.file.status === "done") {
    try {
      const res = await uploadFileUsingPost({}, info.file.originFileObj);
      if (res.data?.code === 0 && res.data.data) {
        const imageUrl = res.data.data;

        // 发送图片消息
        const messageRequest: API.SendMessageRequest = {
          conversationId: currentConversation.value?.id,
          content: imageUrl,
        };

        const sendRes = await sendUserMessageUsingPost(messageRequest);
        if (sendRes.data?.code === 0 && sendRes.data.data) {
          messages.value.push({
            content: imageUrl,
            senderType: 0, // 用户发送
            sequence: Date.now().toString(),
            createdAt: new Date().toISOString(),
          });
          await nextTick();
          scrollToBottom();
        } else {
          message.error(sendRes.data?.message || "发送图片失败");
        }
      }
    } catch (error) {
      message.error("发送图片失败");
    }
  }
};

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 处理图片加载失败
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.src =
    "https://img.js.design/assets/img/64832e1d1b5cdf515c927925.png#2aa0fdda";
};

const loadConversations = async () => {
  try {
    const res = await listUserConversationsUsingPost();
    if (res.data?.code === 0 && res.data.data) {
      conversations.value = res.data.data;
      // 如果有storeId参数，选中对应的会话
      const storeId = route.params.storeId;
      if (storeId) {
        const targetConversation = conversations.value.find(
          (conv) => conv.storeId?.toString() === storeId.toString()
        );
        if (targetConversation) {
          currentConversation.value = targetConversation;
        }
      }
    }
  } catch (error) {
    message.error("获取聊天列表失败");
  }
};

// 添加消息时间格式化函数
const formatMessageTime = (time: string | null | undefined) => {
  if (!time) return "";
  return dayjs(time).format("HH:mm");
};

// 组件卸载前停止轮询
onBeforeUnmount(() => {
  stopPolling();
});

onMounted(() => {
  loadData();
  loadConversations();
});
</script>

<style scoped>
.customer-service-container {
  display: flex;
  height: calc(100vh - 64px);
  background: #f0f2f5;
}

.conversation-list {
  width: 280px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.list-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.list-content {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.conversation-item:hover {
  background: #f5f5f5;
}

.conversation-item.active {
  background: #e6f7ff;
}

.store-avatar {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  background: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}

.store-avatar-text {
  color: white;
  font-size: 16px;
  font-weight: 500;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.store-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.last-time {
  font-size: 12px;
  color: #999;
}

.conversation-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 160px;
}

.unread-badge {
  flex-shrink: 0;
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 0;
  border-radius: 0;
}

.chat-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.product-info-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.product-card {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 12px;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.product-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: 500;
}

.store-info {
  display: flex;
  align-items: center;
  padding: 15px 0;
}

.store-logo {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
}

.store-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.store-status {
  font-size: 12px;
  color: #52c41a;
}

.store-status.online::before {
  content: "";
  display: inline-block;
  width: 6px;
  height: 6px;
  background: #52c41a;
  border-radius: 50%;
  margin-right: 4px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message-received {
  justify-content: flex-start;
}

.message-sent {
  justify-content: flex-end;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
  position: relative;
}

.message-received .message-content {
  background: #f0f2f5;
}

.message-sent .message-content {
  background: #1890ff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: block;
}

.message-sent .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input {
  border-top: 1px solid #f0f0f0;
  padding: 20px;
  background: white;
  border-radius: 0 0 8px 8px;
}

.input-actions {
  margin-bottom: 8px;
}

.send-button {
  margin-top: 8px;
  float: right;
}

:deep(.ant-upload-select) {
  display: inline-block;
}

:deep(.ant-btn-text) {
  color: #666;
}

:deep(.ant-btn-text:hover) {
  color: #1890ff;
  background: rgba(24, 144, 255, 0.1);
}
</style>
